// ColorCalculator.ts

class ColorCaulator {
    size: u32;
    data!: Uint8Array;
    
    constructor(size:u32){
        this.size = size;
        this.data = new Uint8Array(this.size *this.size * 4);

        let pixelDataPtr:usize = changetype<usize>(this.data.buffer);
        for(let i = 0 ; i < this.data.length;i +=4)
        {
            store<u8>(pixelDataPtr + i, 0 ,0);
            store<u8>(pixelDataPtr + i, 0 ,1);
            store<u8>(pixelDataPtr + i, 0 ,2);
            store<u8>(pixelDataPtr + i, 255 ,3);
        }
    }
    GetPixel(x:u32, y:u32, time:u32): u32 {
        const r = (255 * x / this.size) as u32;
        const g = (255 * y / this.size) as u32;
        const b = ((255 * (Math.sin(time * 5) + 1)) as u32) /2;
        const a = 255;

        return (r <<24) | (g <<16) | (b<<8) | a;
    }


    Updata() : void{
        const pixelData = new Uint8Array(this.size *this.size *4);
        let offset = 0;
        for(let y:u32 = 0 ; y < this.size; y++){
            for(let x:u32 = 0; x < this.size; x++){
                let pixelDataPtr:usize = changetype<usize>(pixelData.buffer) + offset;
                for (let index = 0; index < 100;index++){
                    const color = this.GetPixel(x, y, (x + y + index) / 3);
                    store<u8>(pixelDataPtr,(color >> 24) & 0xff, 0)
                    store<u8>(pixelDataPtr,(color >> 16) & 0xff, 1)
                    store<u8>(pixelDataPtr,(color >> 8) & 0xff, 2)
                    store<u8>(pixelDataPtr,color & 0xff, 3)
                }
                offset +=4;

            }
        }
        this.data = pixelData;

    }
}


export function runOnce(): ArrayBuffer {
    const ColorCacu = new ColorCaulator(256);

    // 调用 Updata 方法
    ColorCacu.Updata();


    // 返回图像数据的 ArrayBuffer
    return ColorCacu.data.buffer;
}